package ${packageName}.controller;

import ${packageName}.entity.${className};
import ${packageName}.service.${className}Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;
import java.util.List;
<#if hasDateType>
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
</#if>

<#if hasBigDecimal>
    import java.math.BigDecimal;
</#if>
/**
 * ${tableComment!''} Controller
 * 
 * @author ${author}
 * @date ${.now?string("yyyy-MM-dd HH:mm:ss")}
 */
@RestController
@RequestMapping("/api/${tableName?lower_case}")
@Tag(name = "${className} API", description = "${tableComment!''}相关接口")
@Slf4j
public class ${className}Controller {

    @Autowired
    private ${className}Service ${lowerClassName}Service;

    /**
     * 创建${tableComment!'记录'}
     */
    @PostMapping
    @Operation(summary = "创建${tableComment!'记录'}", description = "创建新的${tableComment!'记录'}")
    public ResponseEntity<${className}> create(@Valid @RequestBody ${className} ${lowerClassName}) {
        try {
            ${className} created = ${lowerClassName}Service.create(${lowerClassName});
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (Exception e) {
            log.error("创建${tableComment!'记录'}失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据ID查询
     */
<#if hasCompositePrimaryKey!false>
    @PostMapping("/findById")
    @Operation(summary = "根据复合主键查询", description = "根据复合主键查询${tableComment!'记录'}")
    public ResponseEntity<${className}> findById(@Valid @RequestBody ${className} queryParam) {
        ${className} result = ${lowerClassName}Service.findByCompositeKey(queryParam);
        if (result != null) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
<#else>
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询", description = "根据ID查询${tableComment!'记录'}")
    public ResponseEntity<${className}> findById(
            @Parameter(description = "记录ID") @PathVariable ${primaryKeyType} id) {
        ${className} result = ${lowerClassName}Service.findById(id);
        if (result != null) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
</#if>

    /**
     * 查询所有记录
     */
    @GetMapping
    @Operation(summary = "查询所有记录", description = "查询所有${tableComment!'记录'}")
    public ResponseEntity<List<${className}>> findAll() {
        List<${className}> result = ${lowerClassName}Service.findAll();
        return ResponseEntity.ok(result);
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "分页查询${tableComment!'记录'}")
    public ResponseEntity<Page<${className}>> findAllByPage(
            @Parameter(description = "页码，从1开始") @RequestParam(defaultValue = "1") int current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        
        Page<${className}> result = ${lowerClassName}Service.findAll(current, size);
        return ResponseEntity.ok(result);
    }

    /**
     * 更新记录
     */
<#if hasSinglePrimaryKey!false>
    @PutMapping("/{id}")
    @Operation(summary = "更新记录", description = "根据ID更新${tableComment!''}")
    public ResponseEntity<${className}> update(
            @Parameter(description = "记录ID") @PathVariable ${primaryKeyType} id,
            @Valid @RequestBody ${className} ${lowerClassName}) {
        try {
            ${lowerClassName}.set${primaryKeyProperty}(id);
            ${className} updated = ${lowerClassName}Service.update(${lowerClassName});
            return ResponseEntity.ok(updated);
        } catch (RuntimeException e) {
            log.error("更新${tableComment!''}失败", e);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("更新${tableComment!''}失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
<#else>
    @PutMapping
    @Operation(summary = "更新记录", description = "更新${tableComment!''}")
    public ResponseEntity<${className}> update(@Valid @RequestBody ${className} ${lowerClassName}) {
        try {
            ${className} updated = ${lowerClassName}Service.update(${lowerClassName});
            return ResponseEntity.ok(updated);
        } catch (RuntimeException e) {
            log.error("更新${tableComment!''}失败", e);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("更新${tableComment!''}失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
</#if>

    /**
     * 根据ID删除
     */
<#if hasCompositePrimaryKey!false>
    @DeleteMapping("/deleteById")
    @Operation(summary = "根据复合主键删除", description = "根据复合主键删除${tableComment!'记录'}")
    public ResponseEntity<Void> deleteById(@Valid @RequestBody ${className} deleteParam) {
        try {
            ${lowerClassName}Service.deleteByCompositeKey(deleteParam);
            return ResponseEntity.noContent().build();
        } catch (RuntimeException e) {
            log.error("删除${tableComment!'记录'}失败", e);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("删除${tableComment!'记录'}失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
<#else>
    @DeleteMapping("/{id}")
    @Operation(summary = "删除记录", description = "根据ID删除${tableComment!'记录'}")
    public ResponseEntity<Void> deleteById(
            @Parameter(description = "记录ID") @PathVariable ${primaryKeyType} id) {
        try {
            ${lowerClassName}Service.deleteById(id);
            return ResponseEntity.noContent().build();
        } catch (RuntimeException e) {
            log.error("删除${tableComment!'记录'}失败", e);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("删除${tableComment!'记录'}失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
</#if>

    /**
     * 批量删除
     */
    @DeleteMapping
    @Operation(summary = "批量删除", description = "批量删除${tableComment!'记录'}")
    public ResponseEntity<Void> deleteAll(@RequestBody List<${primaryKeyType}> ids) {
        try {
            ${lowerClassName}Service.deleteAll(ids);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            log.error("批量删除${tableComment!'记录'}失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 检查记录是否存在
     */
    @GetMapping("/{id}/exists")
    @Operation(summary = "检查记录是否存在", description = "检查指定ID的${tableComment!'记录'}是否存在")
    public ResponseEntity<Boolean> existsById(
            @Parameter(description = "记录ID") @PathVariable ${primaryKeyType} id) {
        boolean exists = ${lowerClassName}Service.existsById(id);
        return ResponseEntity.ok(exists);
    }

    /**
     * 统计总记录数
     */
    @GetMapping("/count")
    @Operation(summary = "统计记录数", description = "统计${tableComment!'记录'}总数")
    public ResponseEntity<Long> count() {
        long count = ${lowerClassName}Service.count();
        return ResponseEntity.ok(count);
    }

<#list columns as column>
    <#if !column.primaryKey>
    /**
     * 根据${column.columnComment!''}查询
     */
    @GetMapping("/by-${column.columnName?lower_case}")
    @Operation(summary = "根据${column.columnComment!''}查询", description = "根据${column.columnComment!''}查询${tableComment!'记录'}")
    public ResponseEntity<List<${className}>> findBy${column.javaPropertyName}(
            @Parameter(description = "${column.columnComment!''}") @RequestParam ${column.javaType} ${column.javaFieldName}) {
        List<${className}> result = ${lowerClassName}Service.findBy${column.javaPropertyName}(${column.javaFieldName});
        return ResponseEntity.ok(result);
    }
    
    </#if>
</#list>
}
